package com.nsgf.library.ui.page.video;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.ClockInBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.VideoListBean;
import com.nsgf.library.databinding.ActivityNsgfRegionHomeVideoBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.ReginVideoInfoListAdapter;
import com.nsgf.library.ui.adapter.VideoTypeListAdapter;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.widget.prckerview.OptionsPickerView;

import java.util.ArrayList;
import java.util.List;

/**
 * 视频监控
 */
public class VideoRegionListActivity extends BaseActivity {
    private CheckWorkAttendanceState mStates;

    private ReginVideoInfoListAdapter mAdapter;
    private VideoTypeListAdapter mAdapterType;
    ActivityNsgfRegionHomeVideoBinding mBinding;

    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(CheckWorkAttendanceState.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new ReginVideoInfoListAdapter(this);
        mAdapterType = new VideoTypeListAdapter(this);

        return new DataBindingConfig(R.layout.activity_nsgf_region_home_video, BR.vm, mStates)
                .addBindingParam(BR.click, new Clickproxy())
                .addBindingParam(BR.adapterType, mAdapterType)
                .addBindingParam(BR.adapterVideo, mAdapter);
    }


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityNsgfRegionHomeVideoBinding) getBinding();
        mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_home_video_map);
        mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);
        mStates.titleBar.set("视频监控");


        getController().displayLoading();
        String url = "file:///android_asset/roadLine/index.html";
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
        mBinding.webView.loadUrl(url);
        // 当页面加载完成后调用JavaScript方法
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                mAccountRequester.getReginVideoList(mStates.search.get());

            }
        });
        mBinding.webView.getWebView().addJavascriptInterface(new WebViewInterface(), "android");

        mAdapterType.setOnItemClickListener((viewId, item, position) -> {

            for (int i = 0; i < mStates.list.get().size(); i++) {
                mStates.list.get().get(i).setChecked(false);
            }
            item.setChecked(true);

            if (item.getList().size() > 0) {
                item.getList().get(0).setChecked(true);
            }
            mStates.videoList.set(item.getList());
            mAdapterType.notifyDataSetChanged();


        });

        mAccountRequester.getReginVideoList().observe(this, listResponseStatus -> {

            getController().dismissLoading();
            if (listResponseStatus.getResponseCode() == 200) {
                mStates.videoList.set(new ArrayList<>());

                List<VideoListBean> list = new ArrayList<>();
                for (VideoListBean videoListBean : listResponseStatus.getData()) {
                    if (videoListBean.getList().size() > 0) {
                        for (VideoListBean.ListBean listBean : videoListBean.getList()) {

                            if (listBean.getList().size() > 0) {
                                list.add(videoListBean);
                                break;
                            }

                        }
                    }
                }

                mStates.list.set(list);

                if (mStates.list.get().size() > 0) {
                    mStates.list.get().get(0).setChecked(true);
                    mAdapterType.notifyDataSetChanged();

                    if (mStates.list.get().get(0).getList().size() > 0) {
                        mStates.list.get().get(0).getList().get(0).setChecked(true);
                    }
                    mStates.videoList.set(mStates.list.get().get(0).getList());
                }

                JSONArray initArray = new JSONArray();
                JSONObject params = null;
                for (VideoListBean dataBean : listResponseStatus.getData()) {
                    String[] area = dataBean.getArea().split(",");
                    if (area.length == 2) {
                        if (null == params) {
                            params = new JSONObject();
                            params.put("lat", area[1]);
                            params.put("lon", area[0]);
                        }
                    }
                    for (VideoListBean.ListBean bean : dataBean.getList()) {
                        for (VideoListBean.ListBean video : bean.getList()) {

                            String[] points = video.getCoordinates().split(",");

                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("callingMode", video.getCallingMode());
                            jsonObject.put("deviceCode", video.getDeviceCode());
                            jsonObject.put("channelId", video.getChannelId());
                            jsonObject.put("lat", points[1]);
                            jsonObject.put("lon", points[0]);
                            jsonObject.put("positionName", video.getDeviceName());
                            jsonObject.put("deviceName", video.getDeviceName());
                            jsonObject.put("status", 5);
                            initArray.add(jsonObject);
                        }
                    }
                }
                callJavaScriptDrawInitPintFunction(params, initArray);

                initJsonData(list);

            } else {
                ToastUtils.showLongToast(listResponseStatus.getMsg());
            }
        });
    }

    /**
     * 三级联动选择视频点位
     *
     * @param jsonBean
     */
    private void initJsonData(List<VideoListBean> jsonBean) {
        options1Items.clear();
        options2Items.clear();
        options3Items.clear();
        options1Items = (ArrayList<VideoListBean>) jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历水库
            ArrayList<VideoListBean.ListBean> cityList = new ArrayList<>();//该改水库 区域列表（第二级）
            ArrayList<ArrayList<VideoListBean.ListBean>> province_AreaList = new ArrayList<>();//该改水库 所有区域列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getList().size(); c++) {//遍历该水库的所有区域
                cityList.add(jsonBean.get(i).getList().get(c));//添加区域
                ArrayList<VideoListBean.ListBean> city_AreaList = new ArrayList<>();//该区域的所有区域列表

                //如果无数据，添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getList().get(c).getList() == null
                        || jsonBean.get(i).getList().get(c).getList().size() == 0) {
                    city_AreaList.add(new VideoListBean.ListBean());
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getList().get(c).getList());
                }
                province_AreaList.add(city_AreaList);//添加该水库所有区域数据
            }

            /**
             * 添加区域数据
             */
            options2Items.add(cityList);


            /**
             * 添加视频点位数据
             */
            options3Items.add(province_AreaList);
        }


    }

    private void callJavaScriptDrawInitPintFunction(JSONObject object, JSONArray list) {
        mBinding.webView.getWebView().evaluateJavascript("zoomToPointVideoList(" + object + "," + list + ");", null);

    }


    /**
     * 聚焦选择的视频点位
     *
     * @param object
     */
    private void callJavaScriptZoomToPointFunction(JsonObject object) {
        mBinding.webView.getWebView().evaluateJavascript("zoomToPoint(" + object + "," + 15 + ");", null);
    }

    public static class CheckWorkAttendanceState extends StateHolder {

        public final State<Integer> mWayMap = new State<>(View.GONE);
        public final State<Integer> mWayList = new State<>(View.VISIBLE);

        public final State<List<VideoListBean>> list = new State<>(new ArrayList<>());
        public final State<List<VideoListBean.ListBean>> videoList = new State<>(new ArrayList<>());

        public final State<String> search = new State<>("");//搜索内容

    }

    private boolean mapList = true;//false 地图 true 列表

    @Override
    protected void onClickSecurity(View v) {
        super.onClickSecurity(v);
        int id = v.getId();
        if (id == R.id.title_bar_clear) {
            mapList = !mapList;
            mBinding.titlebar.titleBarClear.setImageResource(mapList ? R.drawable.ic_home_video_map : R.drawable.ic_home_video_sort);
            if (mapList) {
                mStates.mWayList.set(View.VISIBLE);
                mStates.mWayMap.set(View.GONE);
            } else {
                mStates.mWayList.set(View.GONE);
                mStates.mWayMap.set(View.VISIBLE);
            }
        }
    }

    private ArrayList<VideoListBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<VideoListBean.ListBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<VideoListBean.ListBean>>> options3Items = new ArrayList<>();
    private Thread thread;
    private Thread threadHead;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    public class Clickproxy {

        public void searchVideo() {

            mAccountRequester.getReginVideoList(mStates.search.get());
        }

        public void showPickerView() {
            if (options1Items.size() == 0)
                return;
            // 弹出选择器
            OptionsPickerView pvOptions = new OptionsPickerView.Builder(VideoRegionListActivity.this, (options1, options2, options3, v) -> {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                mBinding.tvNsgfRegionProject.setText(opt1tx);

                JsonObject jsonObject = new JsonObject();

                String[] points = options1Items.get(options1).getList().get(options2).getList().get(options3).getCoordinates().split(",");

                jsonObject.addProperty("lon", points[0]);
                jsonObject.addProperty("lat", points[1]);
                callJavaScriptZoomToPointFunction(jsonObject);
            })
                    .setTitleText("选择视频监控")
                    .setTitleBgColor(getResources().getColor(R.color.white))
                    .setDividerColor(getResources().getColor(R.color.title_text_line))
                    .setTextColorOut(getResources().getColor(R.color.color_C9CDD4))
                    .setTextColorCenter(getResources().getColor(R.color.color_1D2129)) //设置选中项文字颜色
                    .setContentTextSize(16)
                    .build();
//        /*pvOptions.setPicker(options1Items);//一级选择器*/
//        pvOptions.setPicker(options1Items, options2Items);//二级选择器
            pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
            pvOptions.show();

        }
    }


    /**
     * Js调用的JavascriptInterface
     */
    public class WebViewInterface {

        @JavascriptInterface
        public void openDetails(String src) {
            Gson gson = new Gson();
            ClockInBean.DataBean.LateAndEarlyListBean info = gson.fromJson(src, ClockInBean.DataBean.LateAndEarlyListBean.class);

            startActivity(new Intent()
                    .putExtra("callingMode", info.getCallingMode())
                    .putExtra("deviceCode", info.getDeviceCode())
                    .putExtra("channelId", info.getChannelId())
                    .putExtra("deviceName", info.getDeviceName())
                    .putExtra("lat", info.getLat())
                    .putExtra("lon", info.getLon())
                    .setClass(VideoRegionListActivity.this,
                            VideoRegionInfoActivity.class));
        }
    }

}
